﻿using Aop.Api;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PaymentSystemBLL;
using PaymentSystemCommon.AES;
using PaymentSystemCommon.AliAPI;
using PaymentSystemCommon.EnumResult;
using PaymentSystemCommon.Json;
using PaymentSystemCommon.LogHelper;
using PaymentSystemCommon.MD5;
using PaymentSystemCommon.WeiXinAPI;
using PaymentSystemCommon.WFTpayUtils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using Aop.Api.Request;
using Aop.Api.Response;
using PaymentSystemCommon.AliAPI.MD5;
using PaymentSystemModel;
using sdk_cop;
using static sdk_cop.CardbusinessEpaypcConsumptionRequestV1;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using PaymentSystemCommon.ICBC;

namespace PaymentSystemApi.Controllers
{
    /// <summary>
    /// 获取支付二维码|扫码 统一接口
    /// </summary>
    public class OnlinePayController : ApiController
    {
        public HttpResponseMessage PayDo([FromBody] JObject json)
        {
            HttpResponseMessage responseMessage = new HttpResponseMessage();
            PayResultMsg payResultMsg = new PayResultMsg();
            string Operation = json.GetValue("Operation").ToString();
            string data = json.GetValue("Data").ToString();
            if (string.IsNullOrEmpty(Operation) || string.IsNullOrEmpty(data))
            {
                payResultMsg.IsSuccess = false;
                payResultMsg.ErrorMessage = "参数错误！";
            }
            else
            {
                switch (Operation)
                {
                  
                    case "GetICBCQRCode"://工行 聚合支付 阿克苏
                        payResultMsg = GetICBCQRCode(data);
                        break;
                    default:
                        payResultMsg.IsSuccess = false;
                        payResultMsg.ErrorMessage = "参数错误！";
                        break;
                }
            }
            responseMessage.Content = new StringContent(JsonConvert.SerializeObject(payResultMsg), Encoding.GetEncoding("UTF-8"), "text/plain");
            return responseMessage;
        }

        /// <summary>
        /// 工行 聚合支付 阿克苏
        /// </summary>
        /// <param name = "jsondata" ></ param >
        /// < returns ></ returns >
        public PayResultMsg GetICBCQRCode(string jsondata)
        {
            LogHelper.CreateLog("工行聚合支付阿克苏获取收款二维码");
            JObject job = (JObject)JsonConvert.DeserializeObject(jsondata);
            PayResultMsg payResultMsg = new PayResultMsg();
            var orderCode = job["orderCode"].ToString();
            if (orderCode == "")
            {
                payResultMsg.IsSuccess = false;
                payResultMsg.ErrorMessage = StatusCodeEnum.ParameterError.GetEnumText();
                payResultMsg.Data = "请输入订单编号";
                return payResultMsg;
            }
            OrdersBLL ordersBll = new OrdersBLL();
            var _orderList = ordersBll.GetListByWhere("zs_orders", "*", "i_id desc", " and s_code ='" + orderCode + "'");

            if (_orderList.Count <= 0)
            {
                payResultMsg.IsSuccess = false;
                payResultMsg.ErrorMessage = StatusCodeEnum.ParameterError.GetEnumText();
                payResultMsg.Data = "该订单编号不存在";
                return payResultMsg;
            }
            var _orderEntity = _orderList[0];
            var tbbody = job["tbbody"].ToString();
            var CreateIp = job["mch_create_ip"].ToString();
            var icbcConfig = readIcbcJson("icbc");
            /// <returns>非页面服务实现类实例</returns>
            DefaultIcbcClient client = new DefaultIcbcClient(icbcConfig.APP_ID, IcbcConstants.SIGN_TYPE_RSA2, icbcConfig.MY_PRIVATE_KEY, icbcConfig.APIGW_PUBLIC_KEY);
            ///新建服务请求类实例
            QrcodeGenerateRequestV2 request = new QrcodeGenerateRequestV2();
            ///新建服务请求类的业务参数类，该类为内部类
            QrcodeGenerateRequestV2.QrcodeGenerateRequestV2Biz bizContent = new QrcodeGenerateRequestV2.QrcodeGenerateRequestV2Biz();
            ///为请求类设置各种参数
            request.setServiceUrl("https://apipcs4.dccnet.com.cn/api/cardbusiness/qrcode/qrgenerate/V1");
            bizContent.setOutTradeNo(orderCode); //外部订单号
            //bizContent.setStoreCode("");
            bizContent.setMerId(icbcConfig.MerId); //商户编号
            bizContent.setTradeDate(DateTime.Now.ToString("yyyyMMdd")); //交易日期  格式:YYYYMMDD
            bizContent.setTradeTime(DateTime.Now.ToString("hhmmss")); //交易时间hhmmss
            bizContent.setAttach(tbbody); //商户附加信息
            //bizContent.setOrderAmt((_orderEntity.d_total * 100).ToString()); //交易金额
            bizContent.setOrderAmt("1"); //交易金额
            bizContent.setTporderCreateIp(CreateIp);
            bizContent.setNotifyUrl("http://paytest.ylxue.net/API/PayRequest/ResultGHNotify");//该字段非必输项
            bizContent.setNotifyFlag("1");
            bizContent.setPayExpire("1200");
            request.setBizContent(bizContent);
            //同步调用并返回response响应类
            QrcodeGenerateResponseV2 response = null;
            try
            {
                object currenttimemillis = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
                response = (QrcodeGenerateResponseV2)client.execute(request, currenttimemillis + "");
                if (response.isSuccess())
                {
                    //7、业务成功处理，请根据接口文档用response.getxxx()获取同步返回的业务数据
                    payResultMsg.IsSuccess = true;
                    payResultMsg.ErrorMessage = StatusCodeEnum.Success.GetEnumText();
                    payResultMsg.Data = response.getQrcode();
                    return payResultMsg;
                }
                else
                {
                    payResultMsg.IsSuccess = false;
                    payResultMsg.ErrorMessage = StatusCodeEnum.CatchError.GetEnumText();
                    payResultMsg.Data = response.ToString();
                    return payResultMsg;
                }
            }
            catch (System.Net.WebException e) //无法连接到远程服务器，网络异常
            {
                LogHelper.CreateLog(e.ToString());
                throw e;
            }
        }
    

        public IcbcConfig readIcbcJson(string key)
        {
            string jsonfile = HttpContext.Current.Server.MapPath("/Config/icbcConfig.json");//JSON文件路径
            using (System.IO.StreamReader file = System.IO.File.OpenText(jsonfile))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    JObject o = (JObject)JToken.ReadFrom(reader);
                    return JsonHelper.JsonDeserialize<List<IcbcConfig>>(o[key].ToString())[0];
                }
            }
        }
    }
}
